package com.ysalliance.getFan.organization.ui;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ysalliance.getFan.organization.Bean.ClassBean;
import com.ysalliance.getFan.organization.Bean.OrganizationBean;
import com.ysalliance.getFan.organization.Bean.UserBean;
import com.ysalliance.getFan.organization.LucasUtil;
import com.ysalliance.getFan.organization.R;
import com.ysalliance.getFan.organization.adapter.ManagerUserAdapter;
import com.ysalliance.getFan.organization.myview.FunButton;
import com.ysalliance.getFan.organization.network.Network;
import com.ysalliance.getFan.organization.ui.base.LucasBaseActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * 管理员主页
 * @author lucas
 * created at 2020-02-24 14:54
 */
public class AdminMannagerActivity extends LucasBaseActivity {

    //用户协议
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_add_admin)
    TextView tv_add_admin;
    @BindView(R.id.funbt_enter)
    FunButton funbt_enter;    //立即入驻
    @BindView(R.id.tv_tag)
    TextView tv_tag;   //TextView提示
    @BindView(R.id.recycle)
    RecyclerView recycle;


    private ManagerUserAdapter managerUserAdapter;

    public List<UserBean> list = new ArrayList<>();

    public OrganizationBean organizationBean;

    private int page = 1;
    private int count = 1;
    public ClassBean classBean;

    @Override
    public int bindContentView() {
        return R.layout.activity_admin_home;
    }

    @Override
    public void afterView() {
        super.afterView();


        classBean = (ClassBean) getIntent().getSerializableExtra("class_info");

        tv_title.setText("管理员");



        recycle.setVisibility(View.INVISIBLE);
        //列表Adapter初始化z
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycle.setLayoutManager(linearLayoutManager);
        //设置列表默认动画效果
        recycle.setItemAnimator(new DefaultItemAnimator());
        managerUserAdapter = new ManagerUserAdapter(R.layout.item_manager_user, list);
        recycle.setAdapter(managerUserAdapter);
        //列表点击事件
        managerUserAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId() == R.id.tv_remove){
                    remove_admin(list.get(position).getUser_id(),position);
                }
            }
        });



        initClick();

    }



    @Override
    protected void onResume() {
        super.onResume();
        getClassAdmins(classBean.getId(),page);
    }

    public void initClick() {
        //添加管理员
        tv_add_admin.setOnClickListener(v->{
            Intent intent = new Intent(Utils.getApp(), SearchAdminAddActivity.class);
            intent.putExtra("class_info",classBean);
            ActivityUtils.startActivity(intent);
        });







    }



    /**  获取班级所有管理员   */
    public void getClassAdmins(String class_id, int page){

        disposable = Network.getUtilApi()
                .getClassAdmins(class_id, page+"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("获取班级所有管理员的返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){

                            JSONObject jsonObject_data = new JSONObject(  jsonObject.optString("data")  );

                            count = jsonObject_data.optInt("count");
                            tv_title.setText("管理员（"+count+"）");
                            if(count==0){
                                recycle.setVisibility(View.INVISIBLE);
                                tv_tag.setVisibility(View.VISIBLE);
                                funbt_enter.setVisibility(View.VISIBLE);
                            }else {
                                recycle.setVisibility(View.VISIBLE);
                                tv_tag.setVisibility(View.INVISIBLE);
                                funbt_enter.setVisibility(View.INVISIBLE);
                            }

                            List<UserBean> listbeifen =  new Gson().fromJson( jsonObject_data.optString("results"), new TypeToken<List<UserBean>>(){}.getType());

                            if(page == 1){
                                list.clear();
                            }
                            list.addAll(listbeifen);
                            managerUserAdapter.notifyDataSetChanged();




                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }



    /**  移除班级管理员   */
    public void remove_admin(String stu_id, int position){

        disposable = Network.getUtilApi()
                .remove_admin(stu_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("移除班级成员的返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){
                            list.remove(position);
                            managerUserAdapter.notifyDataSetChanged();
                            ToastUtils.showShort("移除成功");
                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }





}
